﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using System.Data;
using XYTXL.Data;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Configuration;
using Newtonsoft.Json;
using NPOI.XSSF.UserModel;

namespace XYTXL.API
{
    public class CommonHelp
    {

        /// <summary>
        /// 绑定类
        /// </summary>
        public class BindData
        {
            /// <summary>
            /// 绑定部门
            /// </summary>
            /// <param name="ddl"></param>
            public void BindBranch(DropDownList ddl, string strISALL = "N")
            {
                if (strISALL == "N")
                {
                    ddl.DataSource = new JH_Auth_BranchB().GetEntities(d => d.DeptCode != 0 && d.DeptCode != 1);

                }
                else
                {
                    ddl.DataSource = new JH_Auth_BranchB().GetEntities(d => d.DeptCode != 0);
                }
                ddl.DataTextField = "DeptName";
                ddl.DataValueField = "DeptCode";
                ddl.DataBind();
            }

            public void BindXWLX(DropDownList ddl)
            {
                ddl.DataSource = new JH_MH_LMGLB().GetEntities(d => d.TopID != 0);
                ddl.DataSource= new JH_MH_LMGLB().GetDTByCommand("select distinct l.Name , p.Name name1,x.Type ID from JH_MH_XWGL x left join JH_MH_LMGL l on x.Type=l.ID left join JH_MH_LMGL p on l.TopID=p.ID order by x.Type");
                ddl.DataTextField = "Name";
                ddl.DataValueField = "ID";
                ddl.DataBind();
            }



            /// <summary>
            /// 绑定年级
            /// </summary>
            /// <param name="ddl"></param>
            public void BindNj(DropDownList ddl, string strISALL = "N")
            {
                ddl.DataSource = new JH_Auth_BranchB().GetDTByCommand("select distinct nj from xy_bj order by nj desc");
                ddl.DataTextField = "nj";
                ddl.DataValueField = "nj";
                ddl.DataBind();
            }

            /// <summary>
            /// 绑定学院
            /// </summary>
            /// <param name="ddl"></param>
            public void BindYx(DropDownList ddl, string strISALL = "N")
            {
                ddl.DataSource = new JH_Auth_BranchB().GetDTByCommand("select xbdm,xbmc from xy_xbdm order by xbmc");
                ddl.DataTextField = "xbmc";
                ddl.DataValueField = "xbdm";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定专业
            /// </summary>
            /// <param name="ddl"></param>
            public void BindZY(DropDownList ddl, string NJ,string XB)
            {
                string strNj = NJ;
                string strXb = XB;
                ddl.DataSource = new JH_Auth_BranchB().GetDTByCommand(" select  distinct zydm,zymc from xy_bj where nj='"+strNj+"' and xbdm='"+strXb+"' ORDER BY zymc");
                ddl.DataTextField = "zymc";
                ddl.DataValueField = "zydm";
                ddl.DataBind();
            }
            public void BindBJ(DropDownList ddl, string NJ, string XB, string zydm)
            {

                ddl.DataSource = new JH_Auth_BranchB().GetDTByCommand(" select  distinct bj,bh from xy_bj where nj='" + NJ + "' and xbdm='" + XB + "'and zydm='" + zydm + "' ORDER BY bj");
                ddl.DataTextField = "bj";
                ddl.DataValueField = "bh";
                ddl.DataBind();
            }

            /// <summary>
            /// 绑定页码
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="Page"></param>
            public void BindPage(DropDownList ddl, int Page)
            {
                ddl.Items.Clear();
                if (Page == 0)
                {
                    ddl.Items.Add(new ListItem() { Text = "1", Value = "1" });
                }
                else
                {
                    for (int i = 1; i <= Page; i++)
                    {
                        ddl.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
                    }
                }

            }

            public void BindAllPeopleSmart(DropDownList ddl)
            {
                ListItem liFirst = new ListItem("请选择", "");
                ddl.Items.Add(liFirst);
                List<JH_Auth_Branch> ListBranch = new JH_Auth_BranchB().GetEntities(d => d.DeptName != "组织机构").ToList();
                foreach (var item in ListBranch)
                {
                    ListItem liBranch = new ListItem(item.DeptName, "optgroup");
                    ddl.Items.Add(liBranch);
                    string strListUsers = new JH_Auth_UserB().GetAllUserListByBranch(item.DeptCode).Trim();
                    if (strListUsers.Length > 0)
                    {
                        foreach (var itemuser in strListUsers.Split(','))
                        {
                            if (itemuser != "admin")
                            {
                                ListItem liUser = new ListItem(new JH_Auth_UserB().GetUserRealName(itemuser), itemuser);
                                ddl.Items.Add(liUser);
                            }

                        }
                    }
                }
            }





            /// <summary>
            /// 绑定审核人（出差请假，经费报销）
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="strClass"></param>
            public void BindSHR(DropDownList ddl, int strRoleCode = 4)
            {

                ddl.DataSource = new JH_Auth_UserRoleB().GetUserDTByRoleCode(strRoleCode);
                ddl.DataTextField = "userrealname";
                ddl.DataValueField = "username";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定栏目
            /// </summary>
            /// <param name="ddl"></param>
            public void BindLM(DropDownList ddl, string strTopID = "0")
            {
                int id = Int32.Parse(strTopID);
                ddl.DataSource = new JH_MH_LMGLB().GetEntities(p => p.TopID == id);
                ddl.DataTextField = "Name";
                ddl.DataValueField = "ID";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定字典类型
            /// </summary>
            /// <param name="ddl"></param>
            public void BindZD(DropDownList ddl, string strType = "0")
            {
                int id = Int32.Parse(strType);
                ddl.DataSource = new JH_Auth_ZiDianB().GetEntities(p => p.Class == id);
                ddl.DataTextField = "TypeName";
                ddl.DataValueField = "ID";
                ddl.DataBind();
            }



            public void BindXM(DropDownList ddl)
            {
                ddl.DataSource = new JH_Auth_BranchB().GetDTByCommand(" SELECT xmdm, xmmc FROM xy_jzxmlb ");
                ddl.DataTextField = "xmmc";
                ddl.DataValueField = "xmdm";
                ddl.DataBind();
            }
        }


        /// <summary>
        /// 获取域名
        /// </summary>
        /// <returns></returns>
        public static string GetDomainName()
        {
            string url = HttpContext.Current.Request.Url.Host;
            if (url.ToLower().StartsWith("http://"))
            {
                url = url.Substring(7);
            }
            if (url.LastIndexOf("/") == -1)
            {
                url += "/";
            }

            return "http://" + url;

        }

        /// <summary>
        /// 从html中提取纯文本
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string StripHT(string strHtml)  //从html中提取纯文本
        {
            Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
            string strOutput = regex.Replace(strHtml, "");//替换掉"<"和">"之间的内容
            strOutput = strOutput.Replace("<", "");
            strOutput = strOutput.Replace(">", "");
            strOutput = strOutput.Replace("&nbsp;", "");
            return strOutput;
        }


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="CorpID"></param>
        /// <param name="Pwd"></param>
        /// <param name="Mobile"></param>
        /// <param name="Content"></param>
        /// <param name="SendTime"></param>
        /// <returns></returns>
        public static string SendDX(string Mobile, string Content, string SendTime)
        {
            try
            {
                string url = "http://www.106818.com:8080/ws/Send2.aspx?CorpID=SY0189&Pwd=7767252812ak@@&Mobile=" + Mobile + "&Content=" + Content + "【企捷科技】";
                WebClient WC = new WebClient();
                WC.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                int p = url.IndexOf("?");
                string sData = url.Substring(p + 1);
                url = url.Substring(0, p);
                byte[] postData = Encoding.GetEncoding("gb2312").GetBytes(sData);
                byte[] responseData = WC.UploadData(url, "POST", postData);
                string returnData = Encoding.GetEncoding("gb2312").GetString(responseData);
                return returnData;

            }
            catch (Exception Ex)
            {
                return Ex.Message;

            }

        }
        /// <summary>
        /// 移除html标签
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string RemoveHtml(string html)
        {
            if (string.IsNullOrEmpty(html)) return html;

            Regex regex = new Regex("<.+?>");
            var matches = regex.Matches(html);

            foreach (Match match in matches)
            {
                html = html.Replace(match.Value, "");
            }
            return html;
        }

        public static HttpWebResponse CreateHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies, string strType = "POST")
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                //request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = strType;
            request.ContentType = "application/x-www-form-urlencoded";

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies, string strType = "POST")
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                //request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = strType;
            request.ContentType = "application/x-www-form-urlencoded";

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.Default);
                return reader.ReadToEnd();

            }
        }
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="table"></param>
        /// <param name="fileName"></param>
        public static MemoryStream RenderToExcel(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            using (table)
            {
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);

                // handling header.
                foreach (DataColumn column in table.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

                // handling value.
                int rowIndex = 1;

                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    foreach (DataColumn column in table.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }

                    rowIndex++;
                }

                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
            }

            //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            //{
            //    byte[] data = ms.ToArray();

            //    fs.Write(data, 0, data.Length);
            //    fs.Flush();
            //    data = null;
            //}
            return ms;
        }
        /// <summary>
        /// excel转换为table
        /// </summary>
        /// <param name="upfile"></param>
        /// <returns></returns>
        public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
        {
            DataTable dt = new DataTable();

            IWorkbook workbook = null;

            Stream stream = upfile.InputStream;

            string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
            if (suffix == "xlsx") // 2007版本
            {
                workbook = new XSSFWorkbook(stream);
            }
            else if (suffix == "xls") // 2003版本
            {
                workbook = new HSSFWorkbook(stream);
            }

            //获取excel的第一个sheet
            ISheet sheet = workbook.GetSheetAt(0);

            //获取sheet的第一行
            IRow headerRow = sheet.GetRow(headrow);

            //一行最后一个方格的编号 即总的列数
            int cellCount = headerRow.LastCellNum;
            //最后一列的标号  即总的行数
            int rowCount = sheet.LastRowNum;
            //列名
            for (int i = 0; i < cellCount; i++)
            {
                dt.Columns.Add(headerRow.GetCell(i).ToString());
            }

            for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
            {
                DataRow dr = dt.NewRow();

                IRow row = sheet.GetRow(i);
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        dr[j] = row.GetCell(j).ToString();
                    }
                }

                dt.Rows.Add(dr);
            }

            sheet = null;
            workbook = null;

            return dt;
        }
        static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
        {
            if (context.Request.Browser.Browser == "IE")
                fileName = HttpUtility.UrlEncode(fileName);
            context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
            context.Response.BinaryWrite(ms.ToArray());
        }
        //
        public static bool HasData(Stream excelFileStream)
        {
            using (excelFileStream)
            {
                IWorkbook workbook = new HSSFWorkbook(excelFileStream);
                if (workbook.NumberOfSheets > 0)
                {
                    ISheet sheet = workbook.GetSheetAt(0);
                    return sheet.PhysicalNumberOfRows > 0;
                }
            }
            return false;
        }





        /// <summary>
        /// 
        /// </summary>
        /// <param name="uploadUrl"></param>
        /// <param name="fileToUpload"></param>
        /// <param name="poststr"></param>
        /// <returns></returns>
        public static string PostFile(string uploadUrl, string fileToUpload, string poststr = "")
        {
            string result = "";

            try
            {
                string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
                webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
                webrequest.Method = "POST";
                StringBuilder sb = new StringBuilder();
                if (poststr != "")
                {
                    foreach (string c in poststr.Split('&'))
                    {
                        string[] item = c.Split('=');
                        if (item.Length != 2)
                        {
                            break;
                        }
                        string name = item[0];
                        string value = item[1];
                        sb.Append("–" + boundary);
                        sb.Append("\r\n");
                        sb.Append("Content-Disposition: form-data; name=\"" + name + "\"");
                        sb.Append("\r\n\r\n");
                        sb.Append(value);
                        sb.Append("\r\n");
                    }
                }
                sb.Append("--");
                sb.Append(boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"file");
                //sb.Append(fileFormName);
                sb.Append("\"; filename=\"");
                sb.Append(Path.GetFileName(fileToUpload));
                sb.Append("\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: application/octet-stream");
                //sb.Append(contenttype);
                sb.Append("\r\n");
                sb.Append("\r\n");
                string postHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                FileStream fileStream = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read);
                long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                webrequest.ContentLength = length;
                Stream requestStream = webrequest.GetRequestStream();
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                byte[] buffer = new Byte[(int)fileStream.Length];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                fileStream.Close();
                WebResponse responce = webrequest.GetResponse();
                requestStream.Close();
                using (Stream s = responce.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        result = sr.ReadToEnd();
                    }
                }

                //if (File.Exists(fileToUpload))
                //{
                //    File.Delete(fileToUpload);
                //}


            }
            catch (Exception ex)
            {
                CommonHelp.WriteLOG(uploadUrl + "|||" + fileToUpload + "|||" + ex.ToString());
            }
            return result;
        }

        private int rep = 0;

        /// <summary>
        /// 生成随机不重复的字符串（分享码用）
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public string GenerateCheckCode(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + this.rep;
            this.rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string GetMD5(string content)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(content, "md5");
        }



        public static string GetConfig(string strKey)
        {
            return ConfigurationManager.AppSettings[strKey] ?? "";
        }

        /// <summary>
        /// 获取数字验证码
        /// </summary>
        /// <param name="codenum"></param>
        /// <returns></returns>
        public static string numcode(int codenum)
        {
            string Vchar = "0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9";
            string[] VcArray = Vchar.Split(',');
            string[] stray = new string[codenum];
            Random random = new Random();
            for (int i = 0; i < codenum; i++)
            {
                int iNum = 0;
                while ((iNum = Convert.ToInt32(VcArray.Length * random.NextDouble())) == VcArray.Length)
                {
                    iNum = Convert.ToInt32(VcArray.Length * random.NextDouble());
                }
                stray[i] = VcArray[iNum];
            }

            string identifycode = string.Empty;
            foreach (string s in stray)
            {
                identifycode += s;
            }
            return identifycode;
        }
        /// <summary>
        /// 登录验证码
        /// </summary>
        /// <param name="codenum"></param>
        /// <returns></returns>
        public static string yzmcode(int codenum)
        {
            string Vchar = "0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
            string[] VcArray = Vchar.Split(',');
            string[] stray = new string[codenum];
            Random random = new Random();
            for (int i = 0; i < codenum; i++)
            {
                int iNum = 0;
                while ((iNum = Convert.ToInt32(VcArray.Length * random.NextDouble())) == VcArray.Length)
                {
                    iNum = Convert.ToInt32(VcArray.Length * random.NextDouble());
                }
                stray[i] = VcArray[iNum];
            }

            string identifycode = string.Empty;
            foreach (string s in stray)
            {
                identifycode += s;
            }
            return identifycode;
        }

        public static string getIPAddress()
        {
            string result = "";
            try
            {

                result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                // 如果使用代理，获取真实IP 
                if (result != null && result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式 
                    result = null;
                else if (result != null)
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。 
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];    //找到不是内网的地址 
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式 
                        return result;
                    else
                        result = null;    //代理中的内容 非IP，取IP 
                }
                if (null == result || result == String.Empty)
                    result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = System.Web.HttpContext.Current.Request.UserHostAddress;

            }
            catch (Exception)
            {
                result = "";
            }
            return result;

        }
        private static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }


        public static string getIpAddr(string ip = "")
        {
            string ipAddr = "";
            try
            {
                string url = "http://1212.ip138.com/ic.asp";
                System.Net.WebClient webClient = new System.Net.WebClient();
                string strSource = webClient.DownloadString(url);

                string regex = @"<center>.+</center>";
                ipAddr = System.Text.RegularExpressions.Regex.Match(strSource, regex).ToString();
                ipAddr = ipAddr.Replace("<center>您的IP是：", "");
                ipAddr = ipAddr.Replace("</center>", "");
                ipAddr = ipAddr.Replace("来自", "");
                ipAddr = ipAddr.Split('：')[1];
                ipAddr = ipAddr.Split(' ')[0];

            }
            catch (Exception ex)
            {
                return "";
            }
            return ipAddr;
        }

        public static void WriteLOG(string err)
        {
            string path = HttpContext.Current.Request.MapPath("/");
            if (!Directory.Exists(path + "/log/"))
            {
                Directory.CreateDirectory(path + "/log/");
            }

            string name = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            if (!File.Exists(path + "/log/" + name))
            {
                FileInfo myfile = new FileInfo(path + "/log/" + name);
                FileStream fs = myfile.Create();
                fs.Close();
            }

            StreamWriter sw = File.AppendText(path + "/log/" + name);
            sw.WriteLine(err + "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sw.Flush();
            sw.Close();

        }


        public string ExportToExcel(string Name, DataTable dt)
        {
            try
            {
                if (dt.Rows.Count > 0)
                {
                    HSSFWorkbook workbook = new HSSFWorkbook();
                    ISheet sheet = workbook.CreateSheet("Sheet1");

                    ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                    HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.Alignment = HorizontalAlignment.Center;
                    HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
                    HeadercellStyle.FillPattern = FillPattern.SolidForeground;
                    HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;

                    //字体
                    NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
                    headerfont.Boldweight = (short)FontBoldWeight.Bold;
                    headerfont.FontHeightInPoints = 12;
                    HeadercellStyle.SetFont(headerfont);


                    //用column name 作为列名
                    int icolIndex = 0;
                    IRow headerRow = sheet.CreateRow(0);
                    foreach (DataColumn dc in dt.Columns)
                    {
                        ICell cell = headerRow.CreateCell(icolIndex);
                        cell.SetCellValue(dc.ColumnName);
                        cell.CellStyle = HeadercellStyle;
                        icolIndex++;
                    }

                    ICellStyle cellStyle = workbook.CreateCellStyle();

                    //为避免日期格式被Excel自动替换，所以设定 format 为 『@』 表示一率当成text來看
                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;


                    NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
                    cellfont.Boldweight = (short)FontBoldWeight.Normal;
                    cellStyle.SetFont(cellfont);

                    //建立内容行
                    int iRowIndex = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        int iCellIndex = 0;
                        IRow irow = sheet.CreateRow(iRowIndex + 1);
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            string strsj = string.Empty;
                            if (dr[i] != null)
                            {
                                strsj = dr[i].ToString();
                            }
                            ICell cell = irow.CreateCell(iCellIndex);
                            cell.SetCellValue(strsj);
                            cell.CellStyle = cellStyle;
                            iCellIndex++;
                        }
                        iRowIndex++;
                    }

                    //自适应列宽度
                    for (int i = 0; i < icolIndex; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        workbook.Write(ms);

                        HttpContext curContext = HttpContext.Current;


                        // 设置编码和附件格式
                        curContext.Response.ContentType = "application/vnd.ms-excel";
                        curContext.Response.ContentEncoding = Encoding.UTF8;
                        curContext.Response.Charset = "";
                        curContext.Response.AppendHeader("Content-Disposition",
                            "attachment;filename=" + HttpUtility.UrlEncode(Name + "_导出文件_" + DateTime.Now.Ticks + ".xls", Encoding.UTF8));

                        curContext.Response.BinaryWrite(ms.GetBuffer());

                        workbook = null;
                        ms.Close();
                        ms.Dispose();

                        curContext.Response.End();
                    }
                }
                return "";
            }
            catch
            {
                return "导出失败！";
            }
        }


        #region 日期函数

        /// <summary>
        /// 某日期是当月的第几周
        /// </summary>
        /// <param name="day"></param>
        /// <param name="WeekStart"></param>
        /// <returns></returns>
        public static int WeekOfMonth(DateTime day, int WeekStart)
        {
            //WeekStart                                                                      
            //1表示 周一至周日 为一周                                                        
            //2表示 周日至周六 为一周                                                        
            DateTime FirstofMonth;
            FirstofMonth = Convert.ToDateTime(day.Date.Year + "-" + day.Date.Month + "-" + 1);
            int i = (int)FirstofMonth.Date.DayOfWeek;
            if (i == 0)
            {
                i = 7;
            }
            if (WeekStart == 1)
            {
                return (day.Date.Day + i - 2) / 7 + 1;
            }
            if (WeekStart == 2)
            {
                return (day.Date.Day + i - 1) / 7;
            }
            return 0;
            //错误返回值0                                                                    
        }

        /// <summary>
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        public static DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /**/
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        public static DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        /**/
        /// <summary>
        /// 取得上个月第一天
        /// </summary>
        /// <param name="datetime">要取得上个月第一天的当前时间</param>
        /// <returns></returns>
        public static DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }

        /**/
        /// <summary>
        /// 取得上个月的最后一天
        /// </summary>
        /// <param name="datetime">要取得上个月最后一天的当前时间</param>
        /// <returns></returns>
        public static DateTime LastDayOfPrdviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddDays(-1);
        }

        /// <summary>
        /// 获取给定时间所属周的第一天
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime FirstWeekDayOfPreviousDate(DateTime datetime)
        {
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            int daydiff = (-1) * weeknow + 1;
            return datetime.AddDays(daydiff);
        }

        /// <summary>
        /// 获取给定时间所属周的最后一天
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime LastWeekDayOfPreviousDate(DateTime datetime)
        {
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            int dayadd = 7 - weeknow;
            return datetime.AddDays(dayadd);
        }

        //转换日期汉字
        public static string WeekName(int d)
        {
            string txt = "";
            switch (d)
            {
                case 7:
                    {
                        txt = "周日";
                    }
                    break;
                case 1:
                    {
                        txt = "周一";
                    }
                    break;
                case 2:
                    {
                        txt = "周二";
                    }
                    break;
                case 3:
                    {
                        txt = "周三";
                    }
                    break;
                case 4:
                    {
                        txt = "周四";
                    }
                    break;
                case 5:
                    {
                        txt = "周五";
                    }
                    break;
                case 6:
                    {
                        txt = "周六";
                    }
                    break;

            }
            return txt;
        }

        #endregion
        public class SessionHelper
        {
            /// <summary>
            /// 根据session名获取session对象
            /// </summary>
            /// <param name="name"></param>
            /// <returns></returns>
            public static object GetSession(string name)
            {
                return HttpContext.Current.Session[name];
            }
            /// <summary>
            /// 设置session,sharejs.com
            /// </summary>
            /// <param name="name">session 名</param>
            /// <param name="val">session 值</param>
            public static void SetSession(string name, object val)
            {
                HttpContext.Current.Session.Remove(name);
                HttpContext.Current.Session.Add(name, val);
            }
        }

    }
}